# -*- coding: utf-8 -*-
"""
popup_handler.py - 弹窗处理器（支持多弹窗配置）

使用示例：
@handle_popups([
	("弹窗1文本", "确定按钮文本"),
	("弹窗2文本", "取消按钮文本")
])
def test_case():
	pass
"""
import time
import functools
import uiautomator2 as u2


def handle_popups(popup_rules):
	"""
	装饰器：自动处理多个指定弹窗

	Args:
		popup_rules: 列表，元素为元组(弹窗文本, 点击文本)
	"""
	
	def decorator(func):
		@functools.wraps(func)
		def wrapper(*args, **kwargs):
			d = u2.connect()
			
			# 1. 预先检查所有弹窗
			for popup_text, click_text in popup_rules:
				if d(text=click_text).exists(timeout=0.1):
					d(text=click_text).click()
				elif d(resourceId=click_text).exists(timeout=0.1):
					d(resourceId=click_text).click()
			
			# 2. 设置watcher监控多个弹窗
			watcher_name = f"POPUP_WATCHER_{hash(str(popup_rules))}"
			watcher = d.watcher(watcher_name)
			
			for popup_text, click_text in popup_rules:
				watcher.when(popup_text).when(click_text).click()
			
			d.watcher.start()
			
			try:
				return func(*args, **kwargs)
			finally:
				d.watcher.stop()
				d.watcher.remove()
		
		return wrapper
	
	return decorator


# 使用示例
@handle_popups([
	('"ZWAP_IOTFAA-354431-WFBJT"不可上网，是否允许 WLAN 助理切换至更好的网络？', "不允许"),
	("系统提示", "确定"),
	("权限请求", "允许"),
	("com.zwcode.p6slite:id/banner", "com.zwcode.p6slite:id/ic_close_cloud_free_dialog")
])
def my_test_case():
	"""实际测试用例"""
	time.sleep(60)


# 执行测试
if __name__ == "__main__":
	my_test_case()